 /*
 * comm_wifi.c
 *
 *  Created on: Oct 15, 2021
 *      Author: Administrator
 */
#include "comm_wifi.h"
#include "machine_stat.h"
#include "lcd_comm.h"
#include "../FWLib/SC95F_Lib/inc/sc95f_usci2.h"
#include "time_8563.h"
#include "protocal.h"
#include "flash.h"

//#include "comm_rinnai.h"
#define DELAY_2MIN        12000
#define DELAY_2S          200
#define DELAY_6S          1200

Comm_t     _WifiCom;
Comm_t     *WifiCom;
static linkSm_t   WifiLinkSm;
static linkSm_t   OldWifiLinkSm;
static bWifiVerRead = 0;

uint8_t wifi_comm_receive_data[F1_00_DATA_LENGTH]={0};
uint8_t wifi_f0_00_data_old[F0_00_DATA_LENGTH]={0};
uint8_t wifi_f0_01_data_old[F0_01_DATA_LENGTH]={0};
uint8_t wifi_f1_00_data_old[F1_00_DATA_LENGTH]={0};
uint8_t wifi_f2_00_data_old[F2_00_DATA_LENGTH]={0};
uint8_t wifi_f2_01_data_old[F2_01_DATA_LENGTH]={0};
uint8_t wifi_f3_01_data_old[F3_00_DATA_LENGTH]={0};
uint8_t wifi_e0_00_data_old[FE_00_DATA_LENGTH]={0};
uint8_t wifi_numlength=0,wifi_numlength1=0;
uint8_t wifi_data_send_times=0;
uint8_t wifi_i=0;
WIFI_STAT1 wifi_stat;
uint8_t wifi_buf[F1_00_DATA_LENGTH];
uint8_t wifi_send_flag=0;//dis_comm=0;
UART2_SEND uart2_send_flag;
//USCI2_HandleInfoDef USCI2_HANDLE_USCI2;
uint16_t wifi_ctrl_block_time = 0;
uint16_t wifi_unlink_wait_period=15; //状态机执行周期个数

/* WIFI版本, 
 * 例如: 00 1C 00 01
 * 00 1C 产品型号 00 测试/开发 01 版本号
 */
uint8_t WifiVersion[4]={0}; 

extern uint8_t key_flag;
extern uint8_t key_num;
extern uint8_t check_num1(uint8_t pdata2);
//extern uint8_t matser_f2;
uint8_t mycmd = 100;

WifiState_t WifiState = WIFI_STA_IDLE;
uint8_t WIFI_SendPackage(uint8_t *pack);
extern uint8_t F0_Data[];
extern uint8_t F2_Data[];
extern uint8_t WifiForwarding(void);
extern void Buzzer_key();
void UART1_SendByte(uint8_t dat);
void Wifi_ReceiveFunc(Comm_t *com);

uint8_t wifi_return_send;


//from aaron,解网串口数组
void wifi_unlink_message(void){
uint8_t *tx = GetSendBuff(WifiCom);	
	tx[3] = 0x53;
	tx[4] = 0x10; //data1
	COM_Send(WifiCom, TEXT_SET, 2);
}

#if 1 /* WIFI Command */
void wifi_reset_message(void){
uint8_t *tx = GetSendBuff(WifiCom);

	tx[0] = CMD_SOFTWEAR_VER;  //data1
	tx[1] = 0x08;  //data2
	tx[2] = 0x31;
	COM_Send(WifiCom, TEXT_SET, 3);
}
void wifi_start_massage(void){
uint8_t *tx = GetSendBuff(WifiCom);

	tx[0] = CMD_SOFTWEAR_VER;  //data1
	tx[1] = 0x08;  //data2
	tx[2] = 0x31;
    COM_Send(WifiCom, TEXT_SET, 3);
}
void wifi_server_end_and_wifi_reset_massage(uint8_t massage){
uint8_t *tx = GetSendBuff(WifiCom);
	tx[0] = CMD_SOFTWEAR_VER;  //data1
	tx[1] = massage;  //data2 
	COM_Send(WifiCom, TEXT_SET, 2);

}

void wifi_f0_00_data(uint8_t massage){
uint8_t *tx = GetSendBuff(WifiCom);
 	memcpy(tx, F0_Data, F0_DATA_SIZE);
	COM_Send(WifiCom, massage, F0_DATA_SIZE);
 }
void wifi_f0_01_data(uint8_t massage){
uint8_t *tx = GetSendBuff(WifiCom);
 	memcpy(tx, F0_Data, F0_DATA_SIZE);
 	COM_Send(WifiCom, massage, F0_DATA_SIZE);
 }
void wifi_f1_00_data(uint8_t massage){
uint8_t *tx = GetSendBuff(WifiCom);	
	
	tx[0] = 0xf1;  //data1
	tx[1] = 0x00;  //data2

	tx[1+1]  = heater_info.Send_SetHeatTemp/10;
	tx[1+2]  = heater_info.Send_SetHeatTemp%10;// 0x00;
	tx[1+3]  = heater_info.err_code_h;
	tx[1+4]  = heater_info.err_code_l;
	tx[1+5]  = heater_info.err_type;
	tx[1+6]  = heater_info.fire_stat;
	tx[1+7]  = heater_info.power_stat;
	tx[1+8]  = heater_info.eco_stat;
	tx[1+9]  = heater_info.eco_mode;
	tx[1+10] = heater_info.SetHeatTempMax/10;
	tx[1+11] = heater_info.SetHeatTempMax%10;	
	tx[1+12] = heater_info.SetHeatTempMin/10;
	tx[1+13] = heater_info.SetHeatTempMin%10;	

	tx[1+14] = heater_info.akey_cycle;
	tx[1+15] = heater_info.cycle_mode;
	tx[1+16] = heater_info.send_super_mode;
	tx[1+17] = heater_info.cold_stat;

    tx[1+18] = heater_info.running_mode;        /* 給湯モード */
    tx[1+19] = heater_info.cool_and_hot;        /*ゆらぎモード*/
    tx[1+20] = heater_info.bathtub_mode;        /*風呂関係状態番号*/
    tx[1+21] = heater_info.BathtubSetWater;     /*風呂設定量*/
    tx[1+22] = heater_info.BathtubRemainWater;  /*風呂残湯量*/ 
    tx[1+23] = CycleOrder.Enable;               /*循环预约开关*/
    tx[1+24] = CycleOrder.TimeTable[0];         /* 循环预约时间 (3byte) */ 
    tx[1+25] = CycleOrder.TimeTable[1];   
    tx[1+26] = CycleOrder.TimeTable[2];   
    tx[1+27] = (CycleDuration>>8)&0xFF;         /*一键循环时间 (2byte)*/
    tx[1+28] = (CycleDuration>>0)&0xFF; 
}

void wifi_f2_00_data(uint8_t massage){
uint8_t *tx = GetSendBuff(WifiCom);	
    memcpy(tx, F2_Data, F2_DATA_SIZE);
	COM_Send(WifiCom, massage, F2_DATA_SIZE);
}
void wifi_f2_01_data(uint8_t massage){
uint8_t *tx = GetSendBuff(WifiCom);	
    memcpy(tx, F2_Data, F2_DATA_SIZE);
 	COM_Send(WifiCom, massage, F2_DATA_SIZE);
}
void wifi_f3_01_data(uint8_t massage){
uint8_t *tx = GetSendBuff(WifiCom);	
    COM_Send(WifiCom, massage, 0);
}
#endif

static uint8_t WifiEvent = 0;

static void SetEvent(uint8_t b){
    WifiEvent |= (1<<b);
}
static void ResetEvent(uint8_t b){
	WifiEvent &= ~(1<<b);
}
static uint8_t GetEvent(uint8_t b){
uint8_t ret = WifiEvent&(1<<b);
    ResetEvent(b);	
   return ret;
}
/** @brief 初始化wifi模块
 */
void WIFI_Init(void){
	WifiCom = &_WifiCom;
	COM_Init(WifiCom);
	WifiCom->PhySendByte = UART1_SendByte;
	WifiCom->ReceiveFunc  = Wifi_ReceiveFunc;
    
    WifiState = WIFI_STA_IDLE;
    WifiLinkSm = SM_LINK_00;
	OldWifiLinkSm = SM_LINK_00;
}



/** @brief WIFI解配网状态机 
 */
void WIFI_LinkFsm(void){
static uint16_t Delay = 0;
uint8_t *tx = GetSendBuff(WifiCom);    
    if(Delay < 0xFFFF) Delay++;

	switch(WifiLinkSm){
		case SM_LINK_00:
		    WifiState = WIFI_STA_IDLE;
			if(EventListener(KEY_WIFI_LONG)){
				Buzzer_key();
				WifiLinkSm = SM_LINK_10;
			}else if(GetEvent(RECV_ROUTE_OK)){ //路由连接OK
                WifiLinkSm = SM_LINK_20;
			}  
		    break;
		case SM_LINK_10:
             tx[0] = 0x10;
             tx[1] = WCMD_LINK_START;
			 COM_Send(WifiCom, TEXT_SET, 2);
			 WifiLinkSm = SM_LINK_10_1;
			 break;
		case SM_LINK_10_1:
		     if(GetEvent(RECV_SMARTLINK_OK)){
			    WifiLinkSm = SM_LINK_11;
			 }else if(Delay >= DELAY_2MIN){
				WifiLinkSm =SM_LINK_00;
			 }else if(GetEvent(RECV_UNLINK_OK)) 
			    WifiLinkSm =SM_LINK_00;
			 else if(GetEvent(RECV_UNLINK_START)) 
			    WifiLinkSm =SM_LINK_00;	 	
		     break;	
		case SM_LINK_11:
		     WifiState = WIFI_STA_LINK_OK;
		     if(Delay >= DELAY_2MIN)
			    WifiLinkSm =SM_LINK_00;
			 else if(GetEvent(RECV_ROUTE_OK)){
				WifiLinkSm = SM_LINK_20;
			}else if(EventListener(KEY_WIFI_LONG)){		
				Buzzer_key();
                WifiLinkSm = SM_LINK_10;			 
			}else if(GetEvent(RECV_UNLINK_OK)) 
			    WifiLinkSm =SM_LINK_00;
			 else if(GetEvent(RECV_UNLINK_START)) 
			    WifiLinkSm =SM_LINK_00;	
		     break;					 			 			 
		case SM_LINK_20:
		    WifiState = WIFI_STA_ROUTE;
		    if(GetEvent(RECV_SERVE_OK)){/* 接收到服务器连接成功CMD */
				
				WifiLinkSm = SM_LINK_30;	
			}else if(EventListener(KEY_WIFI_LONG)){	
				Buzzer_key();
                WifiLinkSm = SM_LINK_40;
			}else if(Delay >= DELAY_2MIN){
				WifiLinkSm = SM_LINK_00;
			}else if(GetEvent(RECV_UNLINK_OK)) 
			    WifiLinkSm =SM_LINK_00;
			else if(GetEvent(RECV_UNLINK_START)) 
			    WifiLinkSm =SM_LINK_00;	
			break;
		case SM_LINK_30:
		    WifiState = WIFI_STA_SUCCESS;
		    if(GetEvent(RECV_ROUTE_FAIL))
			    WifiLinkSm = SM_LINK_31;
			else if(GetEvent(RECV_SERVE_FAIL))
				WifiLinkSm = SM_LINK_31;
		    else if(EventListener(KEY_WIFI_LONG)){
				Buzzer_key();
                WifiLinkSm = SM_LINK_40;
			}else if(GetEvent(RECV_UNLINK_OK)) 
			    WifiLinkSm =SM_LINK_00;
			 else if(GetEvent(RECV_UNLINK_START)) 
			    WifiLinkSm =SM_LINK_00;	 
		     break;	
		case SM_LINK_31:
		     WifiState = WIFI_STA_DISLINK;
		     if(GetEvent(RECV_ROUTE_OK)){
			    WifiLinkSm = SM_LINK_20;
			 }else if(EventListener(KEY_WIFI_LONG)){
				Buzzer_key();
                WifiLinkSm = SM_LINK_40;
			}else if(GetEvent(RECV_UNLINK_OK)) 
			    WifiLinkSm =SM_LINK_00;
			 else if(GetEvent(RECV_UNLINK_START)) 
			    WifiLinkSm =SM_LINK_00;
		     break;			
		case SM_LINK_40:
		     DefaultCycleOrderParam();
			 WifiLinkSm =SM_LINK_40_1;
		case SM_LINK_40_1: 			 
		     WifiState = WIFI_STA_DISLINK_WAIT;
		     if(Delay >= DELAY_6S){
                 WifiLinkSm = SM_LINK_00;
			 }else if(Delay % DELAY_2S == 0){
				COM_DisableRetry(WifiCom);
                tx[0] = 0x10;
                tx[1] = WCMD_UNLINK_START;
				COM_Send(WifiCom, TEXT_SET, 2);	
			 }else if(EventListener(KEY_WIFI_LONG)){
				Buzzer_key();
                WifiLinkSm = SM_LINK_10;
			 }else if(GetEvent(RECV_UNLINK_OK)) 
			    WifiLinkSm =SM_LINK_00;
			 else if(GetEvent(RECV_UNLINK_START)) 
			    WifiLinkSm =SM_LINK_00;
		    break;
	}
    WifiEvent = 0;
    if(OldWifiLinkSm != WifiLinkSm){
		OldWifiLinkSm = WifiLinkSm;
		Delay = 0;
	}
}

void WIFI_Upload(void){
uint8_t *tx = GetSendBuff(WifiCom); 	
static uint16_t delay = 0;
uint8_t forward_cmd = 0;
 
    if(WIFI_IsConnected() == 0) delay = 0;
	else if(delay < 2000) delay++;
	if(WIFI_IsConnected() == 0) return;
	if(COM_IsBusy(WifiCom)) return;
	if(delay < 500) return;
 
	// 数据对比,对所有数据进行对比，如果有变更，立即上传
	wifi_f1_00_data(WIFI_TEXT_INF);
	if(memcmp(tx, wifi_f1_00_data_old, F1_WIFI_DATA_SIZE)!=0 ){
		memcpy(wifi_f1_00_data_old, tx, F1_WIFI_DATA_SIZE);
		COM_Send(WifiCom, WIFI_TEXT_INF, F1_WIFI_DATA_SIZE);		
	}else { /* 转发给wifi */ 
        forward_cmd = WifiForwarding();
		if(forward_cmd){
            switch(forward_cmd){
		       case CMD_F0: 
		         memcpy(tx, F0_Data, F0_DATA_SIZE);
		    	 COM_Send(WifiCom, WIFI_TEXT_INF, F0_DATA_SIZE);
		    	 break;
		    case CMD_F2:	 
		         memcpy(tx, F2_Data, F2_DATA_SIZE);
		    	 memset(F2_Data+1+7, 0, 8); /* 清除一时累积热量和水量 */
		    	 COM_Send(WifiCom, WIFI_TEXT_INF, F2_DATA_SIZE);
		    	 break;
		    }
	    }else if(bWifiVerRead==0){
			tx[0] = 0x10;
			tx[1] = 0x00;
			COM_Send(WifiCom, WIFI_TEXT_GET, 2);
			
		}	
	}
 
}

void WIFI_Task(void){
   COM_Fsm(WifiCom);
   WIFI_LinkFsm(); 
   WIFI_Upload();   
}

void Wifi_10_ReceivedFunc(Comm_t *com){
uint8_t *p = GetRecvBuff(com);	
	
	if(IsReceivedCmd(TEXT_SET) == 0 && IsReceivedCmd(TEXT_RES) == 0){		
		COM_SendNAK(com);
	}else{	
		switch(p[1]){	
            case WCMD_WIFI_VERSION:
                WifiVersion[0] = p[2];
                WifiVersion[1] = p[3];
                WifiVersion[2] = p[4];
                WifiVersion[3] = p[5];
                bWifiVerRead = 1;            
                break;
			case WCMD_RADIO_WAVE: 
			 	COM_SendACK(com);
			 	break;
			case WCMD_ROUTE_STATUS:
			     if(p[2] == 0x31)
				      SetEvent(RECV_ROUTE_OK);
				 else
				      SetEvent(RECV_ROUTE_FAIL);	  
				COM_SendACK(com);
				break;
			case WCMD_ROUTE_INIT:
			     COM_SendACK(com);
			    break;
			case WCMD_ROUTE_INIT_OK:
			     COM_SendACK(com);
			    break;	
			case WCMD_SERVER_STATUS:
				if(p[2] == 0x31)
					SetEvent(RECV_SERVE_OK);
				else
				    SetEvent(RECV_ROUTE_FAIL);
				COM_SendACK(com);
				break;
			case WCMD_LINK_START:
			    SetEvent(RECV_SMARTLINK_START);
				COM_SendACK(com);
				break;			     	
			case WCMD_LINK_END:
				SetEvent(RECV_SMARTLINK_OK);	
				COM_SendACK(com);
				break;  
			case WCMD_UNLINK_START:
				SetEvent(RECV_UNLINK_START);	
				COM_SendACK(com);			
			    break;	                     
            case WCMD_UNLINK_OK:
                wifi_display();
                 
				SetEvent(RECV_UNLINK_OK);
				COM_SendACK(com);
                break;
			default:
				COM_SendNAK(com);
			   break;
			}
	}
}

void Wifi_F4_ReceivedFunc(void){
uint8_t *rx = GetRecvBuff(WifiCom);	
	if(IsReceivedCmd(TEXT_SET) == 0){
	    COM_SendNAK(WifiCom);
		return;
	}

	if(WIFI_IsConnected() == 0 || COM_IsBusy(WifiCom)){
	    COM_SendNAK(WifiCom);
		return;		
	}

	if( IsLock()){
	    COM_SendACK(WifiCom);
		return;	
	}

	switch(rx[1]){
	    case 0x00:  /* 运行SW */
	    	key_flag=1;
	    	key_num=1;
	    	break;
	    case 0x01:   /* Eco SW */
	    	key_flag=1;
	    	key_num=2;
	    	//heat_furnace_f4_txte.furnace_mode=wifi_comm_receive_data[6];
	    	break;
	    case 0x02:  /* Eco热负荷 */
	    	key_flag=1;
	    	key_num=8;
	    	heater_info.eco_mode=rx[2];
	    	//heat_furnace_f4_txte.furnace_off=wifi_comm_receive_data[6];
	    	break;
	    case 0x03: /* 设定温 */
	    	key_flag=1;
	    	key_num=3;
	    	heater_info.Send_SetHeatTemp=(rx[2]*10)+rx[3];
	    	break;
	    case 0x04:  /* A key cycle */
	    	key_flag=1;
	    	key_num=4;
	    	CycleActiveSrc = CYCLE_SRC_KEY;
	    	break;
	    case 0x05:
	    	key_flag=1;
	    	key_num=5;
	    	heater_info.send_cycle_mode=rx[2];
	    	break;
	    case 0x06:   /* super */
	    	key_flag=1;
	    	key_num=6;
	    	break;
	    case 0x07:  /* Runmode */
	        key_flag = 1;
	    	key_num = 7;
	    	/* 模式不写入主板, 需要单独处理 */ 
            SetRunMode(rx[2]); 
	    	break;
	    case 0x0b:
	    	key_flag = 1;
	    	key_num = 0x0b;
	    	heater_info.bathtub_mode = rx[2];
	    	break;
	    case 0x0c:
	    	key_flag=1;
	    	key_num=0x0c;
	    	heater_info.BathtubSetWater = rx[2];
	    	break;
	    case 0x0d:
	    	key_flag=1;
	    	key_num=0x0d;
	    	heater_info.cool_and_hot= rx[2];
			SetRunMode(RUN_PLAIN); 
	    	break;
	    case 0x0f:
	    	CycleOrder.Enable = rx[2];
	    	break;
	    case 0x10:
	    	CycleOrder.TimeTable[0] = rx[2];
	    	CycleOrder.TimeTable[1] = rx[3];
	    	CycleOrder.TimeTable[2] = rx[4];
	    	break;                       
	    case 0x11:
            TimeSync(rx[2], rx[3], rx[4]);
	    	break;
        case 0x12: /* 一键循环时间 */
            CycleDuration = (rx[2]<<8) + rx[3];
            break;
	}
	COM_SendACK(WifiCom);
}

void Wifi_ReceiveFunc(Comm_t *com){
uint8_t *rx = GetRecvBuff(com);	
 
    
    switch(rx[0]){
		case 0x10:
             Wifi_10_ReceivedFunc(com);
		   break;
		case 0xF0:
	        if(IsReceivedCmd(TEXT_SET)){
	        	COM_SendNAK(com);
	        }else if(rx[1]==0x00)
				wifi_f0_00_data(TEXT_RES);
			else if(rx[1] == 0x01) 
				wifi_f0_01_data(TEXT_RES); 
			break;		   
		case 0xF1:
	        if(IsReceivedCmd(TEXT_SET)){
	        	COM_SendNAK(com);
	        }else{
	            wifi_f1_00_data(TEXT_RES);
				COM_Send(WifiCom, TEXT_RES, F1_WIFI_DATA_SIZE);
			}
			break;
		case 0xF2:
		    if(IsReceivedCmd(TEXT_SET))
			    COM_SendNAK(com);
	        else if(rx[1]==0x00)
				wifi_f2_00_data(TEXT_RES);
			else if(rx[1] == 0x01) 
				wifi_f2_01_data(TEXT_RES); 
			break;					   
		case 0xF4:
		     Wifi_F4_ReceivedFunc();
			break;													
	}

}


uint8_t WIFI_IsIdle(void){
	return (WifiState != WIFI_STA_SUCCESS);
}

uint8_t WIFI_IsConnected(void){
    return (WifiState == WIFI_STA_SUCCESS);
}

#if 1 /* WIFI Base function */
void UART1_SendByte(uint8_t dat){
	if(check_num1(dat))
       US2CON0 |= 0x08;
    else
       US2CON0 &= 0xf7;
	US2CON3 = dat;	
}

#endif
